import AsyncStorage from "@react-native-async-storage/async-storage";
import React, { useState, useContext } from "react";
import {
  StyleSheet,
  View,
  Text,
  TextInput,
  TouchableOpacity,
  Image,
  StatusBar,
  Platform,
  ScrollView,
  Alert,
  Keyboard,
} from "react-native";
import Bar from "../../components/bar";
import Blank from "../../components/blank";
import { AntDesign } from "@expo/vector-icons";
import queryApi from "../../api/query";
import personMessageContext from "../../context/personalDetails/personMessageContext";
import companySupplierContext from "../../context/personalDetails/companySupplierContext";

const ManageSuppiler = ({ navigation }) => {
  const { personMessage } = useContext(personMessageContext);
  const { companySupplier, addCompanySupplier, deleteCompanySupplier } =
    useContext(companySupplierContext);

  const [isListShow, setIsListShow] = useState(true);
  const [addEmail, setaddEmail] = useState("");
  const [haveSupplier, setHaveSupplier] = useState(companySupplier.length);

  const addSupplier = async (email) => {
    try {
      const token = await AsyncStorage.getItem("token");
      if (!token) {
        console.log("请求userId出错");
      }
      const data = {
        role: "supplier",
        company_id: personMessage.company_id,
      };
      const response = await queryApi.patch(
        "/user/supplier/" + email + "/add",
        data,
        {
          headers: { Authorization: token },
        }
      );
      if (response.data.message == "success") {
        addCompanySupplier(response.data.newdata);
        setaddEmail("");
        Keyboard.dismiss();
        Alert.alert("成功", "添加供应商成功", [{ text: "确定" }]);
      }
    } catch (error) {
      if (error.response.data.message == "not find user") {
        Keyboard.dismiss();
        Alert.alert("失败", "该用户不存在或该用户已注册过公司", [
          { text: "确定" },
        ]);
      } else {
        Alert.alert("失败", "添加供应商出错", [{ text: "确定" }]);
      }
    }
  };

  const deleteSupplier = async (email) => {
    try {
      const token = await AsyncStorage.getItem("token");
      if (!token) {
        console.log("请求userId出错");
      }
      const data = {
        role: "user",
        company_id: null,
      };
      const response = await queryApi.patch(
        "/user/supplier/" + email + "/delete",
        data,
        {
          headers: { Authorization: token },
        }
      );
      if (response.data.message == "success") {
        deleteCompanySupplier(response.data.newdata);
        Alert.alert("成功", "删除供应商成功", [{ text: "确定" }]);
      } else {
        Alert.alert("失败", "删除供应商出错", [{ text: "确定" }]);
      }
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.backgroundTop}>
        <TouchableOpacity
          onPress={() => navigation.goBack()}
          style={{
            position: "absolute",
            left: 25,
            top: 20,
          }}
        >
          <AntDesign name="close" size={22} color="white" />
        </TouchableOpacity>
      </View>
      <View style={styles.backgroundBottom}>
        <View style={[styles.Modal, styles.manageShadow]}></View>
        <View style={[styles.Modal, styles.manageButton]}>
          <TouchableOpacity onPress={() => setIsListShow(true)}>
            <Image
              style={styles.buttonImage}
              source={require("../../../assets/userMessage/manageSuppiler.png")}
            ></Image>
            <Text
              style={[
                styles.buttonText,
                { color: isListShow ? "#393939" : "#636464" },
              ]}
            >
              管理供应商
            </Text>
          </TouchableOpacity>
        </View>

        <View style={[styles.Modal, styles.addShadow]}></View>
        <View style={[styles.Modal, styles.addButton]}>
          <TouchableOpacity onPress={() => setIsListShow(false)}>
            <Image
              style={styles.buttonImage}
              source={require("../../../assets/userMessage/addSuppiler.png")}
            ></Image>
            <Text
              style={[
                styles.buttonText,
                { color: isListShow ? "#636464" : "#393939" },
              ]}
            >
              添加供应商
            </Text>
          </TouchableOpacity>
        </View>

        {isListShow ? (
          <View style={{ flex: 1 }}>
            <View style={{ marginTop: 90 }}></View>
            {haveSupplier != 0 ? (
              <ScrollView
                showsVerticalScrollIndicator={false}
                style={{ flex: 1 }}
              >
                {companySupplier.map((supplier, index) => (
                  <Bar
                    key={index}
                    image={require("../../../assets/userMessage/addSuppiler.png")}
                    name={supplier.name}
                    email={supplier.email}
                    deleteCompanySupplier={deleteSupplier}
                  />
                ))}
              </ScrollView>
            ) : (
              <Blank />
            )}
          </View>
        ) : (
          <View style={[styles.Modal, styles.addModal]}>
            <View style={{ alignItems: "center" }}>
              <Text style={styles.addText}>添加</Text>
            </View>

            <View style={styles.addMiddle}>
              <Text style={{ fontSize: 16, color: "#afb1b1" }}>员工邮箱</Text>

              <View style={styles.addInput}>
                <TextInput
                  style={{ width: "85%", fontSize: 16 }}
                  value={addEmail}
                  onChangeText={(text) => setaddEmail(text)}
                  maxLength={20}
                ></TextInput>
                <Image
                  style={{ resizeMode: "contain", width: 25, height: 25 }}
                  source={require("../../../assets/userMessage/phone.png")}
                ></Image>
              </View>
            </View>

            <View style={styles.buttonOptions}>
              <TouchableOpacity
                style={styles.cancel}
                onPress={() => {
                  setaddEmail("");
                  setIsListShow(true);
                }}
              >
                <Text style={styles.cancelText}>取消</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.confirm}
                onPress={() => {
                  addSupplier(addEmail);
                }}
              >
                <Text style={styles.confirmText}>确定</Text>
              </TouchableOpacity>
            </View>
          </View>
        )}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: "#fff9ed",
    flex: 1,
    marginTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
  },
  backgroundTop: {
    width: "100%",
    height: "30%",
    // backgroundColor: "#6488e5",
    backgroundColor: "#b7e5e3",
    borderBottomLeftRadius: 30,
    borderBottomRightRadius: 30,
    position: "absolute",
    top: 0,
  },
  backgroundBottom: {
    position: "absolute",
    height: "75%",
    bottom: 0,
    left: 0,
    right: 0,
  },
  Modal: {
    backgroundColor: "#fff",
    borderRadius: 15,
    elevation: 4, //设置阴影角度，通过这个设置有无阴影
    shadowOffset: {
      // 设置阴影偏移量
      width: 0,
      height: 0,
    },
    shadowRadius: 4, // 设置阴影模糊半径
    shadowOpacity: 0.1, // 设置阴影的不透明度
    shadowColor: "gray", // 设置阴影色
  },
  manageShadow: {
    padding: 10,
    height: 110,
    width: "40%",
    opacity: 0.4,
    position: "absolute",
    left: 20,
    top: -65,
  },
  manageButton: {
    padding: 10,
    height: 110,
    width: "40%",
    position: "absolute",
    left: 20,
    top: -55,
  },
  addShadow: {
    padding: 10,
    height: 110,
    width: "40%",
    opacity: 0.4,
    position: "absolute",
    right: 20,
    top: -65,
  },
  addButton: {
    padding: 10,
    height: 110,
    width: "40%",
    position: "absolute",
    right: 20,
    top: -55,
  },
  buttonImage: {
    marginTop: 5,
    marginLeft: 5,
    resizeMode: "contain",
    width: 35,
    height: 35,
    marginBottom: 10,
  },
  buttonText: {
    marginLeft: 5,
    marginBottom: 15,
    fontSize: 16,
    fontWeight: "bold",
  },
  addModal: {
    padding: 20,
    marginTop: 100,
    width: "80%",
    height: 200,
    alignSelf: "center",
  },
  addText: {
    fontSize: 20,
    fontWeight: "bold",
    color: "#636464",
  },
  addMiddle: {
    marginTop: 10,
    height: 65,
    padding: 8,
    alignItems: "flex-start",
  },
  addInput: {
    flexDirection: "row",
    borderBottomColor: "#9ea0a0",
    borderBottomWidth: 1,
  },
  buttonOptions: {
    marginTop: 10,
    flexDirection: "row",
    justifyContent: "center",
    alignContent: "center",
    padding: 15,
    marginBottom: 5,
  },
  cancel: {
    flex: 3,
    padding: 10,
    marginRight: 20,
    borderWidth: 1.5,
    borderColor: "#F9be7d",
    alignItems: "center",
    justifyContent: "center",
    borderRadius: 5,
  },
  confirm: {
    borderRadius: 5,
    flex: 7,
    padding: 10,
    backgroundColor: "#F9be7d",
    alignItems: "center",
    justifyContent: "center",
    elevation: 2, //设置阴影角度，通过这个设置有无阴影
    shadowColor: "gray", // 设置阴影色
  },
  cancelText: {
    fontSize: 16,
    color: "#22254c",
  },
  confirmText: {
    fontSize: 16,
    color: "#fff",
    fontWeight: "bold",
  },
});

export default ManageSuppiler;
